<template>
  <div class="guide-container">
    <el-card class="guide-card">
      <template #header>
        <div class="card-header">
          <h2>微信公众号配置指引</h2>
        </div>
      </template>

      <el-steps :active="activeStep" finish-status="success" class="guide-steps">
        <el-step title="登录微信公众平台" description="访问微信公众平台并登录您的账号" />
        <el-step title="获取接口配置信息" description="在公众号后台获取必要的配置信息" />
        <el-step title="填写配置信息" description="将获取到的信息填写到下方表单中" />
      </el-steps>

      <div class="step-content">
        <div v-if="activeStep === 0">
          <h3>第一步：登录微信公众平台</h3>
          <p>1. 访问 <el-link type="primary" href="https://mp.weixin.qq.com" target="_blank">微信公众平台</el-link></p>
          <p>2. 使用公众号管理员账号登录</p>
        </div>

        <div v-if="activeStep === 1">
          <h3>第二步：获取接口配置信息</h3>
          <p>1. 进入【设置与开发】-【基本配置】页面</p>
          <p>2. 查看/生成 AppID 和 AppSecret</p>
          <p>3. 在服务器配置项中获取消息加解密密钥(EncodingAESKey)</p>
        </div>

        <div v-if="activeStep === 2">
          <h3>第三步：填写配置信息</h3>
          <el-form :model="form" label-width="120px" class="config-form">
            <el-form-item label="公众号名称" required>
              <el-input v-model="form.name" placeholder="请输入公众号名称" />
            </el-form-item>
            <el-form-item label="AppID" required>
              <el-input v-model="form.appId" placeholder="请输入AppID" />
            </el-form-item>
            <el-form-item label="AppSecret" required>
              <el-input v-model="form.appSecret" placeholder="请输入AppSecret" show-password />
            </el-form-item>
            <el-form-item label="AES Key" required>
              <el-input v-model="form.aesKey" placeholder="请输入消息加解密密钥" />
            </el-form-item>
            <el-form-item label="回调URL" required>
              <el-input v-model="callbackUrl" disabled placeholder="系统自动生成">
                <template #suffix>
                  <el-icon class="copy-icon" @click="copyCallbackUrl" v-if="callbackUrl">
                    <CopyDocument />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="Token">
              <el-input v-model="form.token" disabled placeholder="由系统自动生成">
                <template #suffix>
                  <el-icon class="copy-icon" @click="copyToken" v-if="form.token">
                    <CopyDocument />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>

        <div class="step-actions">
          <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
          <el-button type="primary" v-if="activeStep < 2" @click="nextStep">下一步</el-button>
          <el-button type="primary" v-else @click="saveConfig">保存配置</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'
import { getCurrentUserWxConfig, updateWxConfig } from '@/api/app-store/wx'
const activeStep = ref(0)
const form = ref({
  name: '',
  appId: '',
  appSecret: '',
  aesKey: '',
  token: ''
})
const router = useRouter();
const baseWX = "/prod-api/receive-"
console.log(baseWX);

const baseUrl = window.location.origin;

const callbackUrl = computed(() => {
  const appId = form.value.appId;
  return appId ? `${baseUrl}${baseWX}${appId}` : '';
});

// 获取当前用户的公众号配置
onMounted(() => {
  getCurrentUserWxConfig().then(response => {
    const config = response.data
    if (config) {
      form.value = {
        id: config.id || '',
        name: config.name || '',
        appId: config.appId || '',
        appSecret: config.appSecret || '',
        aesKey: config.aesKey || '',
        token: config.token || ''
      }
    }

  }).catch(error => {
    ElMessage.error('获取配置信息失败：' + error.message)
  })
})
const nextStep = () => {
  if (activeStep.value < 2) {
    activeStep.value++
  }
}

const prevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value--
  }
}

const saveConfig = () => {
  if (!form.value.appId || !form.value.appSecret || !form.value.aesKey) {
    ElMessage.error('请填写所有必填项')
    return
  }
  updateWxConfig(form.value).then(response => {
    ElMessage.success('配置保存成功')
    router.push('/wx')
  }).catch(error => {
    ElMessage.error('保存失败：' + error.message)
  })
}

const copyToClipboard = async (text) => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    }
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      document.execCommand('copy');
      textArea.remove();
      return true;
    } catch (error) {
      textArea.remove();
      return false;
    }
  } catch (error) {
    return false;
  }
}

const copyToken = () => {
  if (form.value.token) {
    copyToClipboard(form.value.token)
      .then((success) => {
        if (success) {
          ElMessage.success('Token已复制到剪贴板')
        } else {
          ElMessage.error('复制失败')
        }
      })
  }
}

const copyCallbackUrl = () => {
  if (callbackUrl.value) {
    copyToClipboard(callbackUrl.value)
      .then((success) => {
        if (success) {
          ElMessage.success('回调URL已复制到剪贴板')
        } else {
          ElMessage.error('复制失败')
        }
      })
  }
}
</script>

<style scoped>
.guide-container {
  padding: 20px;
}

.guide-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  text-align: center;
}

.guide-steps {
  margin: 20px 0 40px;
}

.step-content {
  padding: 20px;
}

.config-form {
  max-width: 600px;
  margin: 20px auto;
}

.step-actions {
  margin-top: 30px;
  text-align: center;
}

h3 {
  margin-bottom: 20px;
  color: #409EFF;
}

p {
  line-height: 1.8;
  margin-bottom: 10px;
}

.copy-icon {
  cursor: pointer;
  color: #409EFF;
}

.copy-icon:hover {
  opacity: 0.8;
}
</style>